import JsDataStore from './JsDataStore'
import { JsQtModule } from './JsQtModule'
import HashMap from '@ohos.util.HashMap';

export default class QtJsObjectLoader {

  jsObjects: HashMap<string, Object> = new HashMap();

  constructor() {

  }

  createObject(type: string, name: string, ...args: any[]): Object {
    let modules = JsDataStore.getJsModules();
    let module: JsQtModule = null;
    for (let i = 0; i < modules.length; ++i) {
      if (modules[i].hasJsObjectType(type)) {
        module = modules[i];
        break;
      }
    }

    if (module == null) {
      return null;
    }

    let obj = module.createJsObject(type, name, ...args);
    this.addJsObject(name, obj);
    return obj;
  }

  hasJsObject(name: string) : boolean {
    return this.jsObjects.hasKey(name);
  }

  addJsObject(name: string, obj: Object) : void {
    this.jsObjects.set(name, obj);
  }

  getJsObject(name: string): Object {
    if (this.jsObjects.hasKey(name))
      return this.jsObjects.get(name);
    return undefined;
  }

  deleteJsObject(name: string): boolean {
    if (!this.jsObjects.hasKey(name))
      return false;
    this.jsObjects.remove(name);
    return true;
  }
}